import { ResolveFn } from '@angular/router';
import { Observable, of, delay } from 'rxjs';
import { TableConfig, TableColumn, DateTableColumn } from '@shared/models/table/table-config.models';
import { TableDataSource } from '@shared/models/table/table-datasource';
import { PageLink } from '@shared/models/page/page-link';
import { PageData } from '@shared/models/page/page-data';
import { Direction } from '@shared/models/page/sort-order';
import { DemoUser, mockData } from './table-mock-data';
import { DatePipe } from '@angular/common';
import { TableDemoComponent } from './table-demo.component';

/**
 * 演示用户表格配置解析器
 * 
 * 在路由激活前准备表格配置，通过路由数据传递给表格组件
 * 
 * 注意：resolver 函数不能使用 inject()，需要直接创建实例
 */
export const tableDemoTableConfigResolver: ResolveFn<TableConfig<DemoUser>> = (route) => {
  const config = new TableConfig<DemoUser>();

  // 注意：resolver 函数不在注入上下文中，不能使用 inject()
  // 需要直接创建 DatePipe 实例
  // 使用 'en-US' 作为默认区域（Angular 默认支持，无需额外配置）
  const datePipe = new DatePipe('en-US');

  
  // 配置表单组件（用于添加对话框）
  config.itemComponent = TableDemoComponent;

  // 基本配置
  config.tableTitle = '用户管理';
  config.defaultPageSize = 5;
  config.displayPagination = true;
  config.pageMode = true;
  config.selectionEnabled = true;
  config.searchEnabled = true;
  config.addEnabled = true;
  config.itemsDeleteEnabled = true; // 启用删除功能（会自动在每行添加删除按钮）
  config.defaultSortOrder = { property: 'createdTime', direction: Direction.DESC };
  config.loadDataOnInit = true; // 确保初始化时加载数据

  // 定义列
  config.columns.push(
    new TableColumn<DemoUser>('name','姓名','120px'),
    new TableColumn<DemoUser>('email','邮箱','200px'),
    new TableColumn<DemoUser>('role','角色','100px'),
    new TableColumn<DemoUser>('status','状态','100px'),
    new DateTableColumn<DemoUser>('createdTime', '创建时间', datePipe, '150px')
  );

  
  // 数据获取函数
  config.itemsFetchFunction = (pageLink: PageLink): Observable<PageData<DemoUser>> => {
    const result = getFilteredData(mockData, pageLink);
    return of(result).pipe(delay(300)); // 模拟网络延迟
  };

  // 创建数据源
  config.dataSource = (dataLoadedFunction: (col?: number, row?: number) => void) => {
    const fetchFunction = config.itemsFetchFunction as (pageLink: PageLink) => Observable<PageData<DemoUser>>;
    return new TableDataSource<DemoUser>(
      fetchFunction,
      (item) => true, // 所有项都可选择
      dataLoadedFunction
    );
  };

  // 删除配置
  // 控制哪些行可以删除（可以根据业务需求自定义，例如：管理员不能删除自己）
  config.deleteEnabled = (item) => true; // 所有行都可以删除
  
  // 删除操作函数
  config.deleteItem = (id: string) => {
    // 模拟删除
    const index = mockData.findIndex(u => u.id === id);
    if (index >= 0) {
      mockData.splice(index, 1);
    }
    return of(null).pipe(delay(300));
  };

  config.deleteItemTitle = () => '确认删除';
  config.deleteItemContent = (item) => `确定要删除用户 "${item.name}" 吗？`;
  config.deleteItemsTitle = (count) => `确认批量删除`;
  config.deleteItemsContent = (count) => `确定要删除 ${count} 个用户吗？`;

  // 添加配置（使用 saveItem 保存新数据）
  config.saveItem = (item: DemoUser) => {
    if (!item.id) {
      // 新增：生成ID并设置创建时间
      const newUser: DemoUser = {
        ...item,
        id: String(Date.now()),
        createdTime: Date.now()
      };
      mockData.push(newUser);
      return of(newUser).pipe(delay(300));
    } else {
      // 更新：更新现有数据
      const index = mockData.findIndex(u => u.id === item.id);
      if (index >= 0) {
        mockData[index] = { ...item };
      }
      return of(item).pipe(delay(300));
    }
  };

  // 回调函数
  config.itemAdded = (item) => {
    console.log('用户已添加:', item);
  };

  config.itemUpdated = (item) => {
    console.log('用户已更新:', item);
  };

  config.itemsDeleted = (ids) => {
    console.log('用户已删除:', ids);
  };

  // 直接返回配置对象（同步创建，无需 Observable）
  return config;
};

/**
 * 根据分页和搜索条件过滤数据
 */
function getFilteredData(mockData: DemoUser[], pageLink: PageLink): PageData<DemoUser> {
  let filtered = [...mockData];

  // 搜索过滤
  if (pageLink.textSearch && pageLink.textSearch.trim()) {
    const searchTerm = pageLink.textSearch.toLowerCase();
    filtered = filtered.filter((item) => {
      return (
        item.name.toLowerCase().includes(searchTerm) ||
        item.email.toLowerCase().includes(searchTerm) ||
        item.role.toLowerCase().includes(searchTerm)
      );
    });
  }

  // 排序
  if (pageLink.sortOrder) {
    filtered.sort((a, b) => {
      const property = pageLink.sortOrder!.property;
      const direction = pageLink.sortOrder!.direction === Direction.ASC ? 1 : -1;

      let aValue: unknown = (a as any)[property];
      let bValue: unknown = (b as any)[property];

      if (aValue === bValue) return 0;
      if (aValue === null || aValue === undefined) return 1;
      if (bValue === null || bValue === undefined) return -1;

      if (typeof aValue === 'string' && typeof bValue === 'string') {
        return aValue.localeCompare(bValue) * direction;
      }
      if (typeof aValue === 'number' && typeof bValue === 'number') {
        return (aValue - bValue) * direction;
      }

      return String(aValue).localeCompare(String(bValue)) * direction;
    });
  }

  // 分页
  const totalElements = filtered.length;
  const totalPages = Math.ceil(totalElements / pageLink.pageSize);
  const startIndex = pageLink.page * pageLink.pageSize;
  const endIndex = startIndex + pageLink.pageSize;
  const data = filtered.slice(startIndex, endIndex);

  return {
    data,
    totalElements,
    totalPages,
    hasNext: endIndex < totalElements
  };
}

